$(function() {
    var cols=6;
	var rows_delete=0;
	var mode="add";
	var m_id=0;
	var Curr_Term=1;
    var url='controls/course_model.php';
	if (_dd==1){
		$("#btnAdd").show();
	}else{
		$("#btnAdd").hide();
	}
	
	$("#cboTeacher2").val(0);
	$("#cboTeacher2").attr('disabled','disabled');
	
	var allFields = $( [] ).add( $("#txtDetail"))
							.add( $("#txtFee"))
							.add( $("#txtRemark"))
							.add( $("#txtStudyDate"))
							.add( $("#txtStudyTime"))
							.add( $("#txtStartDate")).add( $("#txtEndDate"));
	var nowTemp = new Date();
	var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);						
	// $('.btndate').datepicker();
	 var checkin = $('.btndate').datepicker({
			onRender: function(date) {
			return date.valueOf() < now.valueOf() ? 'disabled' : '';
		  }
	}).on('changeDate', function(ev) {
	  
	checkin.hide();
   
	}).data('datepicker');

	var checkin2 = $('.btndate2').datepicker({
			onRender: function(date) {
			return date.valueOf() < now.valueOf() ? 'disabled' : '';
		  }
	}).on('changeDate', function(ev) {
	  
	checkin2.hide();
   
	}).data('datepicker');
	
	
	$("#btnPrint").click(function(e){
		e.preventDefault(); 
		
		$("#frmCourse").get(0).setAttribute('action', 'rpt_course.php');
		 
		$("#frmCourse").attr('target', '_blank').submit().removeAttr('target').removeAttr('action');
	
	});
	
	 initialData();
	 
	 function initialData(){
		$.get(url, {"m":"year"},function(data){
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboYear_Search,#cboYear").append(
						$('<option></option>').val(text).html(text)
					);
				});
				$.get(url,{"m":"curryear"},function(data){
					$("#cboYear_Search,#cboYear").val(data);
				});
			}
			
		});
		$.get(url, {"m":"feeType"},function(data){
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboFeeType").append(
						$('<option></option>').val(index).html(text)
					);
				});
			}
		});
	 	$.get(url, {"m":"subject"},function(data){
			var cboObj=eval('('+data+')');	
			var cnt=0;
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					if (cnt==0){
						LoadCBODetail(index);
					}
					$("#cboSubject").append(
						$('<option></option>').val(index).html(text)
					);
					 cnt++;
				});
			}
		});
		
		$.get(url, {"m":"employee"},function(data){
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboTeacher,#cboTeacher2").append(
						$('<option></option>').val(text).html(index)
					);
					 
				});
				$("#cboTeacher,#cboTeacher2").append($('<option></option>').val(9999).html('*ครูจากข้างนอก'));
			}
		});
		$("#cboTeacher,#cboTeacher2").append($('<option></option>').val(0).html(' '));
		$.get(url, {"m":"class"},function(data){
			var Obj=eval('('+data+')');	
			$.each(Obj, function(index, text) {
  				var container = $('#ctrClass');
				   var inputs = container.find('input');
				   var id = inputs.length+1;
 
					$('<input />', { type: 'checkbox', id: 'cb'+id,name:'class_r', value: index }).appendTo( container);
					$('<span />', { 'name': 'cb'+id, text: text,'style':'margin-left:5px;margin-right:30px;' }).appendTo(container);
					 
					if (id % 5==0){
						$('<br/>').appendTo(container);
					}
				   
			});
		})
		 
		
	 	 LoadData('','',"0","",0);
	 }
	 $("#cboCourseType").change(function(e){
		 if ($(this).val() == 1){
			$("#cboTeacher2").val(0);
			$("#cboTeacher2").attr('disabled','disabled');
		 }else{
		 	$("#cboTeacher2").removeAttr('disabled');
		 }
	 });
	 
	 $("#btnSearch").click(function(){
		var _y = $("#cboYear_Search").val();
		var _t = $("#txtTerm_Search").val();
		var _s = $("#cboStatus").val();
		var _d = $("#txtTitle_Search").val();
	
		LoadData(_y,_t,_s,_d,0);
	 });
	 function LoadData(year,term,status,title,id){
        $( "#resultData tbody tr" ).remove();
 
        
        $('#resultData').dataTable( {
			"bProcessing": true,
			"bFilter": false,
			"bLengthChange": false,
			"sAjaxSource": url,
			"oLanguage": {
				"sEmptyTable":     "ไม่พบข้อมูล"
			},
			"bDestroy": true,
			"sServerMethod": "POST",
			"fnServerParams": function ( aoData ) {
					aoData.push( { "name": "m", "value": "load" },
								{"name":"y","value":year},
								{"name":"t","value":term},
								{"name":"s","value":status},
								{"name":"d","value":title}
							);
				},
			"aoColumnDefs":[
				{  "bVisible": false , "aTargets": [ 1 ] },	
				{   "bSortable": true, "aTargets": [ 2 ] ,"sClass":"left"},	
				{   "bSortable": true, "aTargets": [ 3 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 4 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 5 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 6 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 7 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 8 ], "sClass":"center",
					"mRender": function ( data, type, full ) {
						var tmp="";
						if (data=='Y')
							tmp="<span class='label label-success'>ใช้งาน</span>";
						else
							tmp="<span class='label label-warning'>ยกเลิก</span>";
						return tmp;}
				},
				{ "aTargets": [ 9 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
					if (_it==1)
						return "<a href='#popup' data-toggle='modal'><img src='img/edit-file.png' class='btnEdit' style='cursor:pointer;'/></a>";
					else
						return "";
					}
				},
				{"aTargets": [ 10 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
					if (_te==1) 
						return "<a href='#popupConfirm' data-toggle='modal'><img src='img/delete-file.png' class='btnDel' style='cursor:pointer;'/></a>";
					else
						return "";
					}
				}
			],"fnDrawCallback": function ( oSettings ) {
				 
			/* Need to redo the counters if filtered or sorted */
			     var oSettings = this.fnSettings();
                 var iTotalRecords = oSettings.fnRecordsTotal();
				//alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);
				 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=iTotalRecords ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
				} 
		 } );
		 
      }

	 function LoadCBODetail(id){
		$.get(url, {"m":"c","i":id},function(data){
			var obj=eval('('+data+')');	
			 $("#txtDetail").val(obj['detail']);
		});
	 }
	
	
	function checkControl() {
        var bln = true;
	
		if ($("#txtStartDate").val() == "") {
			$("#Error").css('display', '');
			$("#Error").html('กรุณาระบุวัน');
            $("#txtStartDate").attr('style', "width:130px;background-color:#fddedb;border:1px solid #f99891");
            bln = bln && false;
        } else {
            $("#txtStartDate").removeAttr('style');
			$("#Error").css('display', 'none');
			$("#Error").html('กรุณาระบุวัน');
			$("#txtStartDate").attr('style', "width:130px;");
            bln = bln && true;
        }
        return bln;
    }
	function returnDate(id){
		var array = ['','จ.' ,'อ.' ,'พ.' ,'พฤ.' ,'ศ.' ,'ส.' ,'อา.']
		
		return array[id];
	}
	$("#btnAddSubject").live('click',function(){
		var list_class="";
		var class_name="";
		var list_day = "";
		var day_name ="";
		$("#cboMonthFrom,#cboMonthTo").val(1);
		$.each($("input[name=class_r]:checked"),function(index){
			list_class+= $(this).val() +",";
			class_name+= $("span[name="+$(this).attr('id')+"]").html() +", ";
		});
	 
		$.each($("input[name=day]:checked"),function(index){
			list_day+= $(this).val() +",";
			day_name += returnDate($(this).val()) + " - ";
		});
		 
	
		if (list_class == "" ){
			$("#Error").css('display', '');
			$("#Error").html('กรุณาระบุระดับชั้น');
			return;
		}
		else if ( list_day == ""){
			$("#Error").css('display', '');
			$("#Error").html('กรุณาระบุวัน');
			return;
		}
		
		if (checkControl()){
			$("#Error").css('display', 'none');
			class_name=class_name.substring(0,class_name.length-2);
			day_name=day_name.substring(0,day_name.length-2);
			list_day=list_day.substring(0,list_day.length-1);
			list_class=list_class.substring(0,list_class.length-1);
			$("#Error").css('display', 'none');
			
			//var _studydate = $("#txtStudyDate").val();
			var _time = $("#cboTimeFrom option:selected").text() + " " + $("#cboTimeTo option:selected").text() ;
			var _date = $("#txtStartDate").val();
			var _end_date = $("#txtEndDate").val();	 
			$("#table_detail").dataTable().fnAddData([
				0,list_class,list_day, $("#cboTimeFrom option:selected").text() , $("#cboTimeTo option:selected").text(),class_name, day_name, _time, _date,_end_date
			]);
		}else{
			$("#Error").css('display', '');
			return;
		}
	});
	
	$("#cboCarType").change(function(){
		var cid=$(this).val();
		LoadCBODetail(cid);
	});
	
	$("#btnConfirm").live('click',function(){
		$("input").not("[type=submit]").jqBootstrapValidation({preventSubmit: false,
			submitSuccess: function ($form, event) { event.preventDefault();}
		}); 
		var _course_type = $("#cboCourseType").val();
		var _year = $.trim($("#cboYear").val());		
		var _term = $("#txtTerm").val();
		var _teacher = $("#cboTeacher").val();
		var _teacher2="";
		if (_course_type != 1){
			_teacher2 = $("#cboTeacher2").val();
		}
		var _fee_type = $("#cboFeeType").val();
		var _fee = $("#txtFee").val();
		var _subject_id = $("#cboSubject").val();
		var _remark = $("#txtRemark").val();
		var _remark2=$("#txtRemark2").val();
		var _detail = $("#txtDetail").val();
		var _month_from =0;
		var _month_to = 0;
		
		if (_fee_type==1 || _fee_type==5){
			_month_from = $("#cboMonthFrom").val();
			_month_to = $("#cboMonthTo").val();
		}
		var dataSet;
		var list = [];
		var rows = $('#table_detail').dataTable().fnGetNodes();

		for (var i = 0; i < rows.length; i++)
		{
			var row_data = $('#table_detail').dataTable().fnGetData(rows[i]);
			list.push({'for_class': row_data[1], 'study_date': row_data[2],
				'study_time': row_data[3],
				'study_time_end': row_data[4],
				'start_date': row_data[8],
				'end_date': row_data[9]});
		}

		
		if (mode=="add"){
			dataSet={"m":"add"
					,"list":list,
					"year":_year,
					"term":_term ,
					"teacher":_teacher,
					"teacher2":_teacher2,
					"course_type":_course_type,
					"type":_fee_type,
					"cost":_fee,
					"month_from":_month_from,
					"month_to":_month_to,
					"subject_id":_subject_id,
					"remark":_remark,
					"remark2":_remark2,
					"detail":_detail,
					"status":$('input[name=chk]:checked').val()};  
			
		}else{
			dataSet={"m":"edit",
					"id":m_id	,
					"list":list,
					"year":_year,
					"term":_term ,
					"teacher2":_teacher2,
					"course_type":_course_type,
					"teacher":_teacher,
					"type":_fee_type,
					"month_from":_month_from,
					"month_to":_month_to,
					"cost":_fee,
					"subject_id":_subject_id,
					"remark":_remark,
					"remark2":_remark2,
					"detail":_detail,
					"status":$('input[name=chk]:checked').val()}; 
		}
		 
		if (_detail!=""){
			$("#txtDetail").removeAttr('style');
		
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
				//alert(data);
				LoadData($("#cboYear_Search").val(),$("#txtTerm_Search").val(),"0","",0);
				$("#popup").modal('hide');
				
					//allFields.val("");
				}
			});
		}else{
			 
			 $("#txtDetail").attr('style', "background-color:#fddedb;border:1px solid #f99891");
			 alert('กรุณากรอกรายละเอียดเพิ่มเติม');
			 
		}
		 $("input").jqBootstrapValidation("destroy");
		 mode="";
		
	});		
 
	
	 $(".txtamt").keypress(function(e){
		
		if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
			return false;
		}
	});
	
	$("#btnAdd").live('click', function(){
		mode="add";
		ClearData();
	  $("input[name=class_r]").removeAttr('checked','');
	  $("input[name=day]").removeAttr('checked','');
	  $("#Error").css('display', 'none');
	
		allFields.val("");
			 
		SetTableDetail(0);
	});
		
	//Popup confirm delete
	$(".btnDel").live('click',function(){
		var rows = $(this).closest("tr").get(0);
		rows_delete = $('#resultData').dataTable().fnGetPosition(rows);

	}); 
	
	$(".btnDel_detail").live('click', function() {
        var rows = $(this).closest("tr").get(0);
        rows_delete = $('#table_detail').dataTable().fnGetPosition(rows);
        $('#table_detail').dataTable().fnDeleteRow(rows_delete);
        $('#table_detail').dataTable().fnDraw();
    });
	$("#btnDelete").live('click', function(){
		var row_id =$('#resultData').dataTable().fnGetData(rows_delete);
		
		var id=row_id[1];
		 
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"del","id":id},
				 success: function(data){
					$("#popupConfirm").modal('hide');
					$('#resultData').dataTable().fnDeleteRow( rows_delete );
					$('#resultData').dataTable().fnDraw();
				 }
			 });
 
	}); 
	$.get(url, {"m": "term"}, function(data) {
        var obj = eval('(' + data + ')');
        if (obj != null) {
            $.each(obj, function(index, text) {
                $("#txtTerm,#txtTerm_Search").append(
                        $('<option></option>').val(index).html(text)
                        );
            });
			
			$.get(url,{"m":"currterm"},function(data){
					Curr_Term=data;
					$("#txtTerm,#txtTerm_Search").val(data);
			});
        }
    });
	function ClearData(){
		$("input[name=class_r]").removeAttr('checked','');
	    $("input[name=day]").removeAttr('checked','');
		$("#txtRemark").val("");
		 
		$("#txtTerm").val(Curr_Term);
		$("#txtFee").val("0");
		$("#txtRemark2").val("");
		$("#txtDetail").val("");
	}
	$(".btnEdit").live('click',function(){
		mode="edit";
		ClearData();
		 
		$("#Error").css('display', 'none');
		
		var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data =$('#resultData').dataTable().fnGetData(rows);
		 
		m_id = data[1];
		
		$.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"detail","id":m_id},
				 success: function(data){
				 
					var obj = eval('(' + data + ')');
					 
					$("#cboYear").val(obj['year']);		
					$("#txtTerm").val(obj['term']);
					$("#cboTeacher").val(obj['teacher']);
					$("#cboFeeType").val(obj['type_id']);
					$("#txtFee").val(obj['cost']);
					$("#cboSubject").val(obj['subject_id']);
					$("#txtRemark").val(obj['remark']);
					$("#txtRemark2").val(obj['remark2']);
					$("#txtDetail").val(obj['detail']);
					$("#cboCourseType").val(obj['course_type']);
					$("#cboMonthFrom").val(obj['month_from']);
					$("#cboMonthTo").val(obj['month_to']);
					
					if (obj['course_type']==1){
						$("#cboTeacher2").val(0);
						$("#cboTeacher2").attr('disabled','disabled');
					}else{
						$("#cboTeacher2").removeAttr('disabled');
						$("#cboTeacher2").val(obj['teacher2']);
					}
					$("#cboTeacher").val(obj['teacher']);
					if (obj['status']=='Y'){
						$("#chkY").attr('checked','checked');
					}else{
						$("#chkN").attr('checked','checked');
					}
				 }
			 });
			 
			SetTableDetail(m_id);
		//$("#txtDetail").val(data[2]);
		
		/*if (data[8]=='Y'){
			$("#chkY").attr('checked','checked');
		} else{
			$("#chkN").attr('checked','checked');
		} */
	});
	
	function SetTableDetail(id) {
		 
        $("#table_detail").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
            "bPaginate": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_detail"},
							{"name": "id", "value": id}             
				);
            },
            "aoColumnDefs": [
				{"bVisible": false, "aTargets": [1], "sClass": "center"},
				{"bVisible": false, "aTargets": [2], "sClass": "center"},
				{"bVisible": false, "aTargets": [3], "sClass": "center"},
				{"bVisible": false, "aTargets": [4], "sClass": "center"},
                {"bSortable": true, "aTargets": [5], "sClass": "text-left"},
				{"bSortable": true, "aTargets": [6], "sClass": "center"},
                {"bSortable": true, "aTargets": [7], "sClass": "center"},
                {"bSortable": true, "aTargets": [8], "sClass": "center"},
				{"bSortable": true, "aTargets": [9], "sClass": "center"},
                {"aTargets": [10],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                       
                            return "<a href='#'  ><img src='img/delete-file.png' class='btnDel_detail' style='cursor:pointer;'/></a>";
                       
                    }
                }

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });

    }
	  
    
});


